﻿using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace SqliteDAL.DAL
{
    public class BaseDal<T> where T : class, new()
    {
        /// <summary>
        /// 获取上下文EF
        /// </summary>
        public MyContext Db = DbContextFactory.CreateDbContext();


        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="whereLambda">查询条件</param>
        /// <returns></returns>
        public IQueryable<T> LoadEntities(Expression<Func<T, bool>> whereLambda)
        {
            return Db.Set<T>().Where<T>(whereLambda);
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="s">排序的类型</typeparam>
        /// <param name="pageIndex">第几页</param>
        /// <param name="pageSize">每页显示的多少</param>
        /// <param name="totalCount">总记录数</param>
        /// <param name="whereLambda">查询条件</param>
        /// <param name="orderbyLambda">排序的字段</param>
        /// <param name="isAsc">true:升序 false:降序</param>
        /// <returns></returns>
        public IQueryable<T> LoadPageEntities<s>(int pageIndex, int pageSize, out int totalCount, Expression<Func<T, bool>> whereLambda,
            Expression<Func<T, s>> orderbyLambda, bool isAsc)
        {
            var temp = Db.Set<T>().Where<T>(whereLambda);
            totalCount = temp.Count();
            if (isAsc)
            {
                temp = temp.OrderBy<T, s>(orderbyLambda).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize);
            }
            else
            {
                temp = temp.OrderByDescending<T, s>(orderbyLambda).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize);
            }
            return temp;
        }
        /// <summary>
        /// 删除——只对EF打上标记
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        public bool DeleteEntity(T entity)
        {
            Db.Set<T>().Remove(entity);
            Db.Entry<T>(entity).State = EntityState.Deleted;
            return Db.SaveChanges() > 0;
        }
        /// <summary>
        /// 编辑——只对EF打上标记
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        public bool EditEntity(T entity)
        {
            Db.Entry<T>(entity).State = EntityState.Modified;
            return Db.SaveChanges() > 0;
        }
        /// <summary>
        /// 添加——只对EF打上标记
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        public bool AddEntity(T entity)
        {
            Db.Set<T>().Add(entity);
            return Db.SaveChanges()>0;
        }

    }
}
